<template>
    <div class="wasteResource warp">
        <div class="oy-filter">
            <table cellspacing="0px" cellpadding="0px">
                <tbody>
                    <tr>
                        <td width="70px" class="titleStyle">类别:</td>
                        <td class="td_content">
                            <ul  style="height: auto;">
                                <li v-for="(value,i) in categoryList" :key="i" @click="selectCategory(value,i)">
                                    <span :class='{color_w:fjType==i}'>{{value}}</span>
                                </li>
                            </ul>
                        </td>
                    </tr>
                    <tr>
                        <td width="70px" class="titleStyle">省份:</td>
                        <td class="td_content area_box">
                            <ul class="all_item_ul" style="height: auto;">
                                <li v-for="value in areaList" :key="value.id" @click="showAreaChildren(value.name,value.id)">
                                    <span :class='{color_w:lotsAreaStyle==value.id}'>{{value.name}}</span>
                                </li>
                            </ul>
                            <div @click="openMore" class="more_div">
                                <span v-if="showOpen">展开</span>
                                <span v-else>收起</span>
                            </div>
                            <!-- <div v-show="adressAllShow" class="all_item_value">
                                <ul>
                                    <li>
                                      <span class="all_li_span" @click="adressChildAll">全部</span>  
                                    </li>
                                    <li v-for="(val,i) in areaListChildren" :key="i" @click="lotsAreaChild(val.id,i)">
                                        <span :class='{color_w:AreaChildStyle==i}'>{{val.name}}</span>
                                    </li>
                                </ul> 
                            </div> -->
                        </td>
                    </tr>
                    <tr>
                        <td width="70px" class="titleStyle">交易类型:</td>
                        <td class="td_content">
                            <ul>
                                <li v-for="(val,i) in transitionTypeList" :key="i" @click="selectTranType(val,i)">
                                    <span :class='{color_w:tranTypeStyle==i}'>{{val}}</span>
                                </li>
                            </ul>
                        </td>
                    </tr>
                    <tr>
                        <td  width="70px" class="titleStyle">状态:</td>
                        <td class="td_content">
                            <ul>
                                <li v-for="(item,i) in statusList" :key="i" @click="selectStatus(item.id)">
                                    <span :class='{color_w:statusStyle==item.id}'>{{item.val}}</span>
                                </li>
                            </ul>
                        </td>
                    </tr>
                    <tr>
                        <td  width="70px" class="titleStyle">处置信息:</td>
                        <td class="search_Box">
                            <el-input v-model="search" size="mini" placeholder="请输入处置单号或标题" style="width: 280px;" @keyup.enter.native="queryFilterCon"></el-input>
                            <div>
                                <el-button size="mini" type="primary" @click="querySearch">查询</el-button>
                                <el-button size="mini" @click="resetInput">重置</el-button>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="content_list"> 
            <ul class="pai-item-list">
                <li v-for="(val,i) in listWaste" :key="i" class="pai-item">
                    <lbCardItem
                    :image="val.image"
                    :recyclingTitle="val.recyclingTitle"
                    :companyName="val.companyName"
                    :enrollDeadline="val.enrollDeadline"
                    :provinceName="val.provinceName"
                    :cityName="val.cityName"
                    :tradeType="val.tradeType"
                    :status="val.status"
                    :id="val.id"
                    @goParentDetails="goParentDetails"
                    />
                </li>
            </ul>
            <div class="footer_page">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="filterObj.page"
                    :page-sizes="[12,20, 30, 40,50]" :page-size="filterObj.limit" layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>  
            </div>
            
        </div> 
        <el-dialog :visible.sync="loginVisible" width="400px">
            <div class="content_dialog">
                <div class="box" v-show="forget=='1'">
                    <div class="logo_title">
                        <img src="@/assets/logo.png" alt="">
                    </div>
                    <!-- <div class="title-container">
                        <h4>欢迎登录</h4>
                    </div> -->
                    <div class="login_type">
                        <p @click="passWordShow" :class='{l_foucs:loginShow=="1"}'>密码登录</p>
                        <p @click="noteShow" :class='{l_foucs:loginShow=="2"}'>短信登录</p>
                    </div>
                    <el-form
                        v-if="loginShow=='1'"
                        ref="passLoginForm"
                        :model="passLoginForm"
                        :rules="passLoginRules"
                        class="login_form"
                        auto-complete="on"
                        label-position="left"
                        >
                        <el-form-item prop="username">
                            <el-input
                            prefix-icon="el-icon-user"
                            ref="username"
                            v-model="passLoginForm.username"
                            placeholder="用户名/手机号/邮箱"
                            name="username"
                            type="text"
                            tabindex="1"
                            auto-complete="on"
                            clearable
                            />
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input
                            prefix-icon="el-icon-lock"
                            ref="password"
                            v-model="passLoginForm.password"
                            type="password"
                            placeholder="密码"
                            name="password"
                            tabindex="2"
                            auto-complete="on"
                            clearable
                            @keyup.enter.native="loginPasswordEvent"
                            />
                        </el-form-item>
                    </el-form>

                    <el-form
                        v-if="loginShow=='2'"
                        ref="noteLoginForm"
                        :model="noteLoginForm"
                        :rules="noteLoginRules"
                        class="login_form"
                        auto-complete="on"
                        label-position="left"
                        >
                        <el-form-item prop="mobile">
                            <el-input
                            prefix-icon="el-icon-mobile-phone"
                            ref="username"
                            v-model="noteLoginForm.mobile"
                            placeholder="手机号"
                            name="username"
                            type="text"
                            tabindex="1"
                            auto-complete="on"
                            clearable
                            />
                        </el-form-item>
                        <el-form-item prop="code">
                            <el-input 
                            placeholder="请输入验证码" 
                            v-model="noteLoginForm.code"
                            @keyup.enter.native="loginCodeEvent">
                                <el-button slot="append" :disabled="disabled" @click="getverCode(noteLoginForm.mobile)">
                                    <span>{{btnTxt}}</span>
                                </el-button>
                            </el-input>
                        </el-form-item>
                    </el-form>
                        <p @click="forget='2'" class="forgetPW">
                        <span>忘记密码？</span>
                        </p>
                        <!-- :loading="loading" -->
                        <el-button
                            type="danger"
                            style="width: 100%; margin-bottom: 10px;height:48px"
                            @click.native.prevent="handleLogin"
                            >登录</el-button
                        >
                        <el-button
                            plain
                            style="width: 100%;height:48px;margin-left:0px"
                            @click.native.prevent="registerGo"
                            >注册</el-button
                        >
                </div>

                <div class="box" v-show="forget=='2'">
                    <div class="title-container">
                        <h4>忘记密码</h4>
                    </div>
                    <el-form
                        ref="forgetForm"
                        :model="forgetForm"
                        :rules="forgetRules"
                        class="forget_form"
                        auto-complete="on"
                        label-position="left"
                        >
                        <el-form-item prop="mobile">
                            <el-input
                            prefix-icon="el-icon-mobile-phone"
                            ref="username"
                            v-model="forgetForm.mobile"
                            placeholder="手机号"
                            name="username"
                            type="text"
                            tabindex="1"
                            auto-complete="on"
                            clearable
                            />
                        </el-form-item>
                        <el-form-item prop="code">
                            <el-input 
                            placeholder="请输入验证码" 
                            v-model="forgetForm.code"
                            @keyup.enter.native="loginCodeEvent">
                                <el-button slot="append" :disabled="disabled" @click="getverCode(forgetForm.mobile)">
                                    <span>{{btnTxt}}</span>
                                </el-button>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input placeholder="请输入新密码" type="password" v-model="forgetForm.password" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item prop="checkPass">
                            <el-input placeholder="请再次输入新密码" type="password" v-model="forgetForm.checkPass" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-form>
                        <el-button
                            type="danger"
                            style="width: 100%; margin-bottom: 10px;height:48px"
                            @click.native.prevent="forgetPassword"
                            >提交</el-button>
                            <div class="goback" @click="forget='1'">
                                <i class="el-icon-back">返回</i>
                            </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import lbCardItem from '@/components/card/lbCardItem.vue';
import {getCode,verifyCode,changePasswordUser} from '@/api/user'
import {InterfaceDockingList,AreaList} from '@/api/interface'
import {getUserInfoID,_debounce} from '@/utils/auth'
export default{
    name:'wasteResource',
    components:{
        lbCardItem
    },
    data(){
        var validatePass = (rule, value, callback) => {
            if (value === '') {
            callback(new Error('请输入密码'));
            } else {
            if (this.forgetForm.checkPass !== '') {
                this.$refs.forgetForm.validateField('checkPass');
            }
            callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
            callback(new Error('请再次输入密码'));
            } else if (value !== this.forgetForm.password) {
            callback(new Error('两次输入密码不一致!'));
            } else {
            callback();
            }
        };
        const validatePhone = (rule, value, callback) => {
            // 判断输入框中是否输入手机号
            if (!value) {
                callback(new Error('手机号不能为空'))
            }
            //正则表达式进行验证手机号，从1开始，第二位是345789中的任意一位，以9数字结尾
            if (!/^1[345789]\d{9}$/.test(value)) {
                callback(new Error('手机号格式不正确'))
            }
            callback()
        }
        return{
            total:0,
            listWaste:[],
            uid:null,
            loginVisible:false,
            passLoginForm: {
                username: "",
                password: "",
            },
            passLoginRules:{
                username: [{ required: true, trigger: 'blur', message: '用户名不能为空' }],
                password: [{ required: true, trigger: 'blur', message: '密码不能为空' }]
            },
            noteLoginForm:{
                mobile: "",
                code: "", 
            },
            noteLoginRules:{
                mobile:[
                { required: true, trigger: 'blur', message: '请输入11位手机号'},
                { required: true, trigger: 'blur', min: 11, max: 11, message: '长度不符合'},
                { required: true, trigger: 'blur', validator: validatePhone}
                ],
                code:[
                { required: true, trigger: 'blur', message: '请输入6位验证码'},
                { required: true, trigger: 'blur', min: 6, max: 6,message: '验证码错误'}    
                ],
            },
            loginShow:'1',
            btnTxt: "获取验证码",
            // 是否禁用  即点击之后一段时间内无法再点击
            disabled: false,
            time: 0,
            queryId:'',
            l_foucs:'l_foucs',
            forget:'1',
            forgetForm:{
                mobile:'',
                code: "", 
                password: "",
                checkPass:''
            },
            forgetRules:{
                mobile:[{ required: true, trigger: 'blur', message: '请输入手机号'},{ required: true, trigger: 'blur', min: 11, max: 11, message: '长度不符合'},],
                code: [{ required: true, trigger: 'blur', message: '请输入验证码'},{ required: true, trigger: 'blur', min: 6, max: 6,message: '验证码错误'} ], 
                password: [{ required: true, validator: validatePass, message: '请输入密码'}],
                checkPass:[{ required: true, validator: validatePass2, message: '请再次重复密码'}],
            },
            allNumber:null,
            color_w:'color_w',
            categoryList:['全部','废金属','周转材料','机械设备','活动房屋','机动车辆','电子电器','电线电缆','办公用品','小型机具','库存物资','其他'],
            transitionTypeList:['全部','竞价','询价'],
            statusList:[
                {id:'99',val:'全部'},
                {id:'1',val:'报名中'},
                {id:'2',val:'进行中'},
                {id:'3',val:'待成交'},
                {id:'4',val:'已成交'},
                {id:'5',val:'已流标'},
            ],
            areaList:[], //省份
            areaListChildren:[], //市区
            adressAllShow:false,
            fjType:'0', //类别
            lotsAreaStyle:null, //省份
            AreaChildStyle:null, //市区
            tranTypeStyle:0, //交易类型
            statusStyle:'99',//状态
            filterObj:{
                page:1,
                limit:12,
                keywords:'',
                provinceName:'',
                sortName:'',
                tradeTypeName:'',
                status:''
            },
            search:'',
            showOpen:true,
            surplusList:[],
            areaAllList:[]
        }
    },
    created(){
        var info = getUserInfoID();
        if(info){
            this.uid = JSON.parse(info).id;
        }else{
            this.uid = null;
        }
        // {page:this.page,limit:this.limit}
        this.getList({page:this.filterObj.page,limit:this.filterObj.limit});
        this.allNumber = window.setInterval(() => {
            setTimeout(() => {
                this.getList({page:this.filterObj.page,limit:this.filterObj.limit});
            },0);
        }, 300000);
        this.filterContent()
    },
    destroyed(){
        clearInterval(this.allNumber);
    },
    watch:{
        filterObj:{
            handler(val){
                this.getList(val);
            },
            deep: true
        }
    },
    methods:{
        getList(obj){
            InterfaceDockingList(obj).then(res=>{
                this.listWaste = res.data;
                this.total = res.count;
            });
        },
        filterContent(){
            AreaList().then(res=>{
                this.areaAllList=res.data.slice(0,12);
                this.areaList=res.data.slice(0,12);
                this.surplusList = res.data.slice(12,res.data.length+1);
            }); 
        },
        openMore(){
            if(this.showOpen){
                this.showOpen = false;
               let newList = this.areaAllList.concat(this.surplusList);
               this.areaList = newList;
            }else{
                this.showOpen = true;
               this.areaList = this.areaAllList;
            }
        },
        //选择类别
        selectCategory(typeName,i){
            if(i == 0){
                this.filterObj.sortName = '';
            }else{
                this.filterObj.sortName = typeName;

            }
            this.fjType = i;
        },
        //选择省份
        showAreaChildren(name,id){
            this.filterObj.provinceName = name;
            this.lotsAreaStyle = id;
        },
        //交易类型
        selectTranType(name,i){
            if(i==0){
                this.filterObj.tradeTypeName = '';
            }else{
                this.filterObj.tradeTypeName = name;
            }
            this.tranTypeStyle = i;
        },
        //状态
        selectStatus(id){
            if(id == '99'){
                this.filterObj.status = '';
            }else{
                this.filterObj.status = id;
            }
            this.statusStyle = id;
        },
        queryFilterCon(){
            this.filterObj.keywords= this.search; 
        },
        querySearch(){
            this.filterObj.keywords= this.search; 
        },
        resetInput(){
            this.filterObj.keywords= ''; 
            this.search=''; 
        },
        goParentDetails(idval){
            this.queryId = idval;
            // if(this.uid){
                // let {href}= this.$router.resolve({
                //     path: '/wasteResource/detail',   // 这里写的是要跳转的路由地址
                //     query: {id:idval}// 这里写的是页面参数
                // });
                // window.open(href, '_blank');   
                // console.log(idval,'333333');

                this.$router.push({ path: '/wasteResource/detail',query: {id:idval } });

            // }else{
                // this.$message({
                //     message: '请先登录',
                //     type: 'warning'
                // });
                // this.$router.push({path:'/login'})
                // this.loginVisible = true;
            // }
        },
        passWordShow(){
            this.loginShow ='1';
        },
        noteShow(){
            this.loginShow ='2'
        },
        // 点击注册
        registerGo(){
            this.$router.push({path:'/user/register'})
        },
        // 点击登录
        handleLogin:_debounce(function(){
            if(this.loginShow =='1'){
                this.$refs.passLoginForm.validate(valid => {
                    if (valid) { 
                        //账号密码登录
                        // console.log('zhixing')
                        this.$store.dispatch('bidderLogin', this.passLoginForm).then(() => {
                            // this.loginVisible = false;
                            this.$router.push({ path: '/wasteResource/detail',query: {id:this.queryId } });
                            // let {href}= this.$router.resolve({
                            //     path: '/wasteResource/detail',   // 这里写的是要跳转的路由地址
                            //     query: {id:this.queryId }// 这里写的是页面参数
                            // });
                            // window.open(href, '_blank');   
                            // this.loading = false
                        }).catch(() => {
                            // this.loading = false
                        })
                    }
                });
                
            }else{
                this.$refs.noteLoginForm.validate(valid => {
                    if (valid) { 
                        //手机号验证码登录
                        this.$store.dispatch('bidderMobileLogin', this.noteLoginForm).then(() => {
                            // this.loginVisible = false;
                            this.$router.push({ path: '/wasteResource/detail',query: {id:this.queryId } })

                            // this.$router.push({ path: '/' })
                            // let {href}= this.$router.resolve({
                            //     path: '/wasteResource/detail',   // 这里写的是要跳转的路由地址
                            //     query: {id:this.queryId }// 这里写的是页面参数
                            // });
                            // window.open(href, '_blank');   

                            // this.loading = false
                        }).catch(() => {
                            // this.loading = false
                        })
                    }
                });
                
            }
        }),
        getverCode(mobileVal){
            // 校验手机号码
            if (!mobileVal) {
                //号码校验不通过
                this.$message({
                message: '请输入手机号',
                type:'warning',
                });
                //正则判断 从1开始，第二位是35789中的任意一位，以9数字结尾
            } else if (!/1[35789]\d{9}/.test(mobileVal)) {
                // 失去焦点后自动触发校验手机号规则
            } else {
                this.time = 60;
                this.disabled = true;
                //调用倒计时方法
                this.timer();
                getCode({mobile:mobileVal}).then(res=>{
                    this.$message({
                        message: res.msg,
                        type: 'success'
                    })
                })
            }
        },
        // 倒计时方法
        timer() {
            if (this.time > 0) {
                this.time--;
                // console.log(this.time);
                // this.btnTxt = this.time + "s后重新获取验证码";
                this.btnTxt = "已发送" + this.time + 's';
                setTimeout(this.timer, 1000);
            } else {
                this.time = 0;
                this.btnTxt = "获取验证码";
                this.disabled = false;
            }
        },
         // 密码输入框 回车键盘事件
         loginPasswordEvent(){
            this.$refs.passLoginForm.validate(valid => {
                if (valid) { 
                    this.$store.dispatch('bidderLogin', this.passLoginForm).then(() => {
                        this.$store.dispatch('getUserInfo');
                        // this.loginVisible = false;
                        this.$router.push({ path: '/wasteResource/detail',query: {id:this.queryId } });

                        // let {href}= this.$router.resolve({
                        //     path: '/wasteResource/detail',   // 这里写的是要跳转的路由地址
                        //     query: {id:this.queryId }// 这里写的是页面参数
                        // });
                        // window.open(href, '_blank');   

                        // this.loading = false
                    }).catch(() => {
                        // this.loading = false
                    });
                }
            }); 
        },
        // 手机号登录-验证码 回车键盘事件
        loginCodeEvent(){
            this.$refs.noteLoginForm.validate(valid => {
                if (valid) { 
                     //手机号验证码登录
                    this.$store.dispatch('bidderMobileLogin', this.noteLoginForm).then(() => {
                        this.$store.dispatch('getUserInfo');
                        this.loginVisible = false;
                        this.$router.push({ path: '/wasteResource/detail',query: {id:this.queryId } })

                        // let {href}= this.$router.resolve({
                        //     path: '/wasteResource/detail',   // 这里写的是要跳转的路由地址
                        //     query: {id:this.queryId }// 这里写的是页面参数
                        // });
                        // window.open(href, '_blank');   
                        // this.loading = false
                    }).catch(() => {
                        // this.loading = false
                    })
                }
            });
        },
         //忘记密码
         forgetPassword(){
            this.$refs.forgetForm.validate(valid => {
                if (valid) { 
                    verifyCode({mobile:this.forgetForm.mobile,code:this.forgetForm.code}).then(res=>{
                        if(res.code == 200){
                            this.modificationPassword();
                        }else{
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            })
                        }
                    }).catch(err=>{
                        if(err.code== -200){
                            this.$message({
                                message: err.msg,
                                type: 'error'
                            })
                        }
                    });
                }
            });
        },
        modificationPassword(){
            changePasswordUser({mobile:this.forgetForm.mobile,password:this.forgetForm.password}).then(res=>{
                if(res.code == 200){
                    this.$message({
                        message: '密码修改成功',
                        type: 'success'
                    });
                    this.forget='1';
                    this.$refs.forgetForm.resetFields();
                }else{
                    this.$message({
                        message: res.msg,
                        type: 'error'
                    })
                }
            }).catch(err=>{
                this.$message({
                    message: err.msg,
                    type: 'error'
                })
            });
        },
        // ---------分页
        handleSizeChange(val) {
            this.filterObj.limit = val;
        },
        //----- 分页---------
        handleCurrentChange(val) {
            this.filterObj.page = val;
        }
    }
}
</script>
<style lang="less" scoped>
@import '@/styles/index.less';
.wasteResource{
    .l_foucs{
        color:@base-color;
        font-weight: bold;
    }
    .color_w{
        color:@base-color;
    }
    .oy-filter{
        margin: 20px 0 10px 0;
        background-color: #f8f4f4;
        table{
            width: 100%;
            border-collapse: collapse;
            border-top: 2px dotted #fff;
            tr{
                .titleStyle{
                    height: 26px;
                    padding: 0 20px;
                    font-weight: 600;
                    color: #333;
                    line-height: 16px;
                    white-space: nowrap;
                }
                .search_Box{
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 10px;
                }
                .area_box{
                    position: relative;
                    ul{
                        overflow: hidden;
                        padding-right: 140px;
                    }
                    
                    .more_div{
                        position: absolute;
                        right: 20px;
                        top: 20px;
                        cursor: pointer;
                    }
                }
                .td_content{
                    ul{
                        display: flex;
                        justify-content: space-between;
                        flex-wrap: wrap;
                        &:after{
                                content: '';
                                flex: auto;
                                // width: 90px;
                            }
                        li{
                            margin: 10px 0;
                            cursor: pointer;
                            // padding-right: 28px;
                            span{
                                padding: 0px 16px;
                            }
                            span:hover{
                                color: @base-color;
                            }
                            span:focus{
                                color: @base-color;
                            }
                        }
                    }
                }
                td {
                    font-size: 14px;
                    border-bottom: 2px dotted #fff;
                    padding: 10px 0;
                    text-align: left;
                }
            } 
        }
        
    }
    .content_list{
        .pai-item-list{
            display: grid;
            justify-content: space-between;
            grid-template-columns: repeat(auto-fill,285px);
            grid-gap: 20px;
            li{
                // margin: 6px;
                // display: inline-block;
                // cursor: pointer;
                
            }
        }
        .footer_page{
            margin: 26px 0;
            /deep/ .el-pagination{
                display: flex;
                justify-content: center;
            }
        }
    }
    .content_dialog{
        display: flex;
        align-items: center;
        justify-content: center;
        .box{
            padding: 0px 30px 25px 30px;
            width: 350px;
            overflow: hidden;
            // background: #ffffff;
            .logo_title{
                margin-bottom: 20px;
                img{
                    width: 100px;
                    vertical-align: middle;
                }
            }
            .login_type{
                display: flex;
                justify-content: space-around;
                font-size: 16px;
                padding: 20px 0px;
                p{
                    cursor: pointer;
                }
            }
            .forgetPW{
                text-align: right;
                color: #999;
                font-size: 14px;
                span{
                    display: inline-block;
                    padding: 6px;
                    cursor: pointer;
                }
            }
        }
    }
    /deep/.el-dialog{
        background-image: url('@/assets/home/login_bg_new.png');
        background-size:cover;
        background-repeat: no-repeat;
        border-radius: 18px;
    }
    
}
</style>